/*
 * ------------------------------------------------------------------
 * Copyright © 2017, Hangzhou  DtDream Technology Co.,Ltd. All rights reserved.
 * ------------------------------------------------------------------
 * Product : DTWare
 * Module Name : MOC
 * Date Created: 2017-08-04
 * Description :
 * ------------------------------------------------------------------
 * Modification History * DATE Name Description
 * ------------------------------------------------------------------
 * 2017-08-04 z0228 refactor project
 * ------------------------------------------------------------------
 */
package com.gitee.booting.dspi.processor;

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by zhangh on 2016/6/2.
 * Author  : zhangh
 *
 * @version : 1.0.0
 */
public class Parser {
    public final static String DSPI_METADATA = "META-INF/dspi.meta";
    public final static String DSPI = "com.gitee.booting.dspi.Dspi";
    private static final PathMatchingResourcePatternResolver RESOLVER = new PathMatchingResourcePatternResolver(Parser.class.getClassLoader());

    public static Map<String, Object> parse() {
        Map<String, Object> meta = new HashMap<>();
        try {
            final Resource[] resources = RESOLVER.getResources("classpath*:" + DSPI_METADATA);
            for (Resource resource : resources) {
                BufferedReader br = new BufferedReader(new InputStreamReader(resource.getInputStream()));
                String text = br.lines().collect(Collectors.joining("\n"));
                text = text.replaceAll("\\\\\n", "");
                int pos;
                for (String one : text.split("\\n")) {
                    pos = one.indexOf("=");
                    meta.put("spring.cloud.nacos.discovery.metadata.[" + one.substring(0, pos) + "]", one.substring(pos + 1));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return meta;
    }
}
